<?php
// 应用公共文件

/**
 * 计算给定 IP 地址和子网掩码的广播地址
 * @copyright ChatGPT https://chat.openai.com/chat
 * @param string $ip
 * @param string $subnetMask 子网掩码
 * @return string 广播地址
 * @throws Exception 如果 IP 地址或子网掩码无效，则抛出异常
 */
function getBroadcast(string $ip, string $subnetMask='255.255.255.0'): string
{
    // 判断 IP 地址和子网掩码是否有效
    if (!filter_var($ip, FILTER_VALIDATE_IP)) {
        throw new Exception('Invalid IP address:'.$ip);
    }
    $binarySubnet = decbin(ip2long($subnetMask));
    if (!substr_count($binarySubnet, '0') + 1 == strlen($binarySubnet) - strpos($binarySubnet, '0')) {
        throw new Exception(' Invalid subnet mask:'.$subnetMask);
    }

    // 计算广播地址并返回
    return long2ip((ip2long($ip) & ip2long($subnetMask)) | (~ip2long($subnetMask) & ip2long('255.255.255.255')));
}

function msg($code, $msg='', $data=null): \think\response\Json
{
    return json([
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ]);
}

/**
 * 判断字符串是否为 Json 格式
 * @param string $data
 * @param bool $assoc
 * @return bool
 */
function isJson(string $data = '', bool $assoc = false): bool
{
    $data = json_decode($data, $assoc);
    if (($data && is_object($data)) || (is_array($data) && !empty($data))) {
        return true;
    }
    return false;
}

/**
 * @param string $url
 * @param array $data
 * @return bool|string
 */
function http_post(string $url, array $data)
{
    $curl = curl_init();
    $postData = http_build_query($data);
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_HTTPHEADER => array(
            'Content-Type: application/x-www-form-urlencoded'
        ),
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    return $response;

}

function socket_post($host, $port, $data): string
{
    $timeout = 30;
    $socket = fsockopen($host, $port, $errno, $errStr, $timeout);
    if (!$socket) {
        return "Error: $errno - $errStr";
    } else {
        $postData = http_build_query($data);
        $request = "POST /path/to/endpoint HTTP/1.1\r\n".
            "Host: $host\r\n".
            "Content-Type: application/x-www-form-urlencoded\r\n".
            "Content-Length: ".strlen($postData)."\r\n".
            "Connection: close\r\n\r\n".
            $postData;
        fwrite($socket, $request);
        $response = '';
        while (!feof($socket)) {
            $response .= fgets($socket, 1024);
        }
        fclose($socket);
        return $response;
    }
}